package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.Question;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;


@Service
public class TodayBestService {

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;

    @Autowired
    private QuestionService questionService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    @Reference(version = "1.0.1")   //.0是MD .1是ES
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;

    public TodayBest queryTodayBest() {
        User user = UserThreadLocal.get();
        //查询推荐用户
        TodayBest todayBest = recommendUserService.queryTodayBest(user.getId());
        if (null == todayBest) {
            //给出默认推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(100L);
        }
        //补全信息
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(todayBest.getId());
        if (null == userInfo) {
            return null;
        }
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        todayBest.setAge(userInfo.getAge());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
        return todayBest;
    }


    public PageResult queryRecommendation(RecommendUserQueryParam recommendUserQueryParam) {
        User user = UserThreadLocal.get();
        PageResult pageResult = new PageResult();
        pageResult.setPage(recommendUserQueryParam.getPage());
        pageResult.setPagesize(recommendUserQueryParam.getPagesize());
        PageInfo<RecommendUser> pageInfo = recommendUserService.queryRecommendUserList(user.getId(), recommendUserQueryParam.getPage(), recommendUserQueryParam.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();
        //如果未查询到,需要使用默认推荐类表
        if (CollectionUtils.isEmpty(records)) {
            String[] split = StringUtils.split(defaultRecommendUsers, ",");
            for (String s : split) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                recommendUser.setScore(RandomUtils.nextDouble(70, 100));
                records.add(recommendUser);
            }
        }
        //填充个人信息

        //收集推荐用户的id
        HashSet<Long> userIds = new HashSet<>();
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        //用户id参数
        queryWrapper.in("user_id", userIds);
        //判断是否筛选
        //性别
        if (StringUtils.isNotEmpty(recommendUserQueryParam.getGender())) {
            //queryWrapper.eq("sex",StringUtils.equals(recommendUserQueryParam.getGender(),"man")?1:2);
        }
        //城市
        if (StringUtils.isNotEmpty(recommendUserQueryParam.getCity())) {
            //queryWrapper.like("city",recommendUserQueryParam.getCity());
        }
        //年龄
        if (null != recommendUserQueryParam.getAge()) {
            //queryWrapper.le("age",recommendUserQueryParam.getAge());
        }
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);
        if (CollectionUtils.isEmpty(userInfoList)) {
            //没有查询到
            return pageResult;
        }
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setAge(userInfo.getAge());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));
            for (RecommendUser record : records) {
                if (record.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    double score = Math.floor(record.getScore());    //取整
                    todayBest.setFateValue((long) score);
                    break;
                }
            }
            todayBests.add(todayBest);
        }
        //排序
        Collections.sort(todayBests, ((o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue()));
        pageResult.setItems(todayBests);
        return pageResult;
    }

    public TodayBest queryTodayBest(Long userId) {

        User user = UserThreadLocal.get();

        TodayBest todayBest = new TodayBest();
        //补全信息
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(userId);
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        double score = this.recommendUserService.queryScore(userId, user.getId());
        if (score == 0) {
            score = 98; //默认分值
        }

        todayBest.setFateValue(Double.valueOf(score).longValue());

        return todayBest;
    }

    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if (null != question) {
            return question.getTxt();
        }
        return "";
    }

    /**
     * 回复陌生人问题，发送消息给对方
     *
     * @param userId
     * @param reply
     * @return
     */
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", userInfo.getNickName());
        msg.put("strangerQuestion", this.queryQuestion(userId));
        msg.put("reply", reply);

        try {
            String msgStr = MAPPER.writeValueAsString(msg);

            String targetUrl = ssoUrl + "/user/huanxin/message";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);

            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

            ResponseEntity<Void> responseEntity = restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //查询当前用户的地理位置
        User user = UserThreadLocal.get();
        UserLocationVo userLocationVo = userLocationApi.queryByUserId(user.getId());
        Double longitude = userLocationVo.getLongitude();
        Double latitude = userLocationVo.getLatitude();
        //查询附件的好友
        List<UserLocationVo> userLocationVoList = userLocationApi.queryUserFromLocation(longitude, latitude, Integer.valueOf(distance));
        if (CollectionUtils.isEmpty(userLocationVoList)) {
            return null;
        }
        Set<Long> userIds = new HashSet<>();
        for (UserLocationVo locationVo : userLocationVoList) {
            userIds.add(locationVo.getUserId());
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            queryWrapper.eq("sex", SexEnum.MAN);
        } else if (StringUtils.equalsIgnoreCase(gender, "woman")) {
            queryWrapper.eq("sex", SexEnum.WOMAN);
        }
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);
        List<NearUserVo> nearUserVoList = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationVoList) {
            if (locationVo.getUserId().longValue() == user.getId()) {
                continue;
            }
            for (UserInfo userInfo : userInfoList) {
                if (locationVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    NearUserVo nearUserVo = new NearUserVo(locationVo.getUserId(), userInfo.getLogo(), userInfo.getNickName());
                    nearUserVoList.add(nearUserVo);
                    break;
                }
            }
        }
        return nearUserVoList;
    }

    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        PageInfo<RecommendUser> pageInfo = recommendUserService.queryRecommendUserList(user.getId(), 1, 50);
        List<RecommendUser> recommendUserList = pageInfo.getRecords();
        if (CollectionUtils.isEmpty(recommendUserList)) {
            String[] split = StringUtils.split(defaultRecommendUsers, ",");
            for (String s : split) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                recommendUserList.add(recommendUser);
            }
        }

        Set<RecommendUser> recommendUsers = new HashSet<>();
        int showCount = Math.min(10, recommendUserList.size());
        while (recommendUsers.size() < showCount) {
            recommendUsers.add(recommendUserList.get(RandomUtils.nextInt(0, recommendUserList.size())));
        }

        Set<Long> userIds = new HashSet<>();
        for (RecommendUser recommendUser : recommendUsers) {
            userIds.add(recommendUser.getUserId());
        }
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);
        List<TodayBest> todayBestList=new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setFateValue(0L);
            todayBestList.add(todayBest);
        }
        return todayBestList;
    }

    public void likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        String id = userLikeApi.saveUserLike(userId, likeUserId);
        if (StringUtils.isEmpty(id)){
            return;
        }
        if (userLikeApi.isMutualLike(userId,likeUserId)){
            //互相喜欢就加为好友
            imService.contactsUsuer(likeUserId);
        }
    }

    public void disLikeUser(Long likeUserId) {
        userLikeApi.deleteUserLike(UserThreadLocal.get().getId(), likeUserId);
    }
}
